package com.im.utils.Redis;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.nio.charset.StandardCharsets;

@Component
public class OldRedisScriptManager {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    private String scriptSha;
    public String getScriptSha() {return scriptSha;}

    private static final String LUA_SCRIPT = "local key = KEYS[1]\n" +
            "local run_id_key = 'redis_run_id'\n" +
            "local run_id = redis.call('GET', run_id_key)\n" +
            "if not run_id then\n" +
            "    run_id = redis.call('INFO', 'server'):match('run_id:(%w+)')\n" +
            "    redis.call('SET', run_id_key, run_id)\n" +
            "end\n" +
            "local last_entry = redis.call('ZRANGE', key, -1, -1, 'WITHSCORES')\n" +
            "local new_score\n" +
            "if #last_entry > 0 then\n" +
            "    local last_run_id = last_entry[1]\n" +
            "    local last_score = tonumber(last_entry[2])\n" +
            "    if last_run_id == run_id then\n" +
            "        new_score = last_score + 1\n" +
            "    else\n" +
            "        new_score = tonumber(redis.call('TIME')[1]) * 1000000 + 1\n" +
            "    end\n" +
            "else\n" +
            "    new_score = tonumber(redis.call('TIME')[1]) * 1000000 + 1\n" +
            "end\n" +
            "redis.call('ZADD', key, new_score, run_id)\n" +
            "return new_score";
    @PostConstruct
    public void loadScript() {
        // 将 Lua 脚本预加载到 Redis 中，获取 SHA1 标识
        scriptSha = redisTemplate.execute((connection) ->
                        connection.scriptLoad(LUA_SCRIPT.getBytes(StandardCharsets.UTF_8)),
                true);
        System.out.println("Lua 脚本已加载，SHA1: " + scriptSha);
    }
}